package com.kermitye.studentsys;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private DatabaseHelper helper;
    private SQLiteDatabase db;

    public DBManager(Context context) {
        helper = new DatabaseHelper(context);
        db = helper.getReadableDatabase();
    }


    public void add(Student student) {
        ContentValues cv = new ContentValues();
        cv.put("name", student.name);
        cv.put("speciality", student.speciality);
        cv.put("clazz", student.clazz);
        db.insert("Studnets", null, cv);
    }

    public void delete(Student student) {
        String[] args = {student.id + ""};
        db.delete("Studnets", "id=?", args);
    }

    public void update(Student student) {
        ContentValues cv = new ContentValues();
        cv.put("name", student.name);
        cv.put("speciality", student.speciality);
        cv.put("clazz", student.clazz);
        String[] args = {student.id + ""};
        db.update("Studnets", cv, "id=?", args);
    }

    public List<Student> query() {
        Cursor cursor = db.query("Studnets", null, null, null, null, null, null);
        List<Student> datas = new ArrayList<>();
        while (cursor.moveToNext()) {
            long id = cursor.getLong(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String speciality = cursor.getString(cursor.getColumnIndex("speciality"));
            String clazz = cursor.getString(cursor.getColumnIndex("clazz"));

            Student student = new Student();
            student.id = id;
            student.name = name;
            student.speciality = speciality;
            student.clazz = clazz;
            datas.add(student);
        }
        cursor.close();
        return datas;
    }

}
